﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Xml.XPath;

using TheOutfield.UmbExt.UniversalMediaPicker;
using TheOutfield.UmbExt.UniversalMediaPicker.Extensions;
using TheOutfield.UmbExt.UniversalMediaPicker.Providers;
using TheOutfield.UmbExt.UniversalMediaPicker.Xslt;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.web;

namespace umbraco.blog4.DataTypes.DoctypeProvider {
    public class DoctypeProvider : AbstractProvider {
        public DoctypeProvider() : base() { }
        public DoctypeProvider(string config) : base(config) { }

        public override string Alias {
            get { return "Document Type Provider"; }
        }

        public override TheOutfield.UmbExt.UniversalMediaPicker.Interfaces.IConfigControl ConfigControl {
            get { return new Config(); }
        }

        public override TheOutfield.UmbExt.UniversalMediaPicker.Interfaces.ICreateControl CreateControl {
            get { throw new NotImplementedException(); }
        }

        public override MediaItem GetMediaItemById(string id) {
            try
            {
                DocumentType d = new DocumentType(Convert.ToInt32(id));
                return new MediaItem() { Icon = "", Id = d.Id.ToString(), HasChildren = d.HasChildren, Selectable = true, Title = d.Text };
            }
            catch
            {
                return null;
            }
        }

        public override IList<MediaItem> GetMediaItems(string parentId) {
            List<MediaItem> m = new List<MediaItem>();
            IEnumerable<DocumentType> l;
            if (parentId == "-1") {
                l = (from y in DocumentType.GetAllAsList() where y.MasterContentType == 0 select y);
            } else {
                l = (from y in DocumentType.GetAllAsList() where y.MasterContentType == Convert.ToInt32(parentId) select y);
            }
            foreach (DocumentType x in l) {
                MediaItem mi = new MediaItem() { Icon = "", Id = x.Id.ToString(), HasChildren = (x.HasChildren), Selectable = true, Title = x.Text };
                m.Add(mi);
            }
            return m;
        }
    }

    public class DoctypeXsltExtensions : AbstractXsltExtension {
        public static int GetValue(string value) {
            XmlDocument d = new XmlDocument();
            d.LoadXml(value);
            int typeId = 0;
            int.TryParse(d.SelectSingleNode("value").InnerText, out typeId);

            return typeId;
        }
    }
}